package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

import Models.POSBeerView;

public class POSBeerViewPresenter {
	public ArrayList<POSBeerView> tryJSONParseArray(String input){
		ArrayList<POSBeerView> beer = new ArrayList<POSBeerView>();
		try{
			JSONObject jsonObj = null;
			jsonObj = XML.toJSONObject(input);
			JSONObject jsonAllObjects = jsonObj.getJSONObject("beers");
				if(!jsonAllObjects.isNull("beer")){
					Object item = jsonAllObjects.get("beer");
					if(item instanceof JSONArray){
						JSONArray jArray = (JSONArray)item;
						for(int i=0; i < jArray.length(); i++){
							JSONObject jObject = jArray.getJSONObject(i);
							beer.add(createBeerFromJSONObject(jObject));
						}
					} else {
						JSONObject jObject = (JSONObject)item;
						beer.add(createBeerFromJSONObject(jObject));
					}
				}
			return beer;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public POSBeerView tryJSONParse(String input){
		try{
			JSONObject jsonObj = null;
			jsonObj = XML.toJSONObject(input);
			JSONObject jsonHop = jsonObj.getJSONObject("beer");
			POSBeerView beer = createBeerFromJSONObject(jsonHop);
			return beer;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public POSBeerView createBeerFromJSONObject(JSONObject jsonBeer){
		POSBeerView beer = new POSBeerView();
		try{
			beer.setID(jsonBeer.getInt("bId"));
			beer.setName(jsonBeer.getString("bName"));
			return beer;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(POSBeerView item){
		try{
			JSONObject json = new JSONObject();
			json.put("bId", item.getID());
			json.put("bName", item.getName());
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
}
